<template>
	<view>
		<view class="top">
			<image class="tiaozhuan" src="../../../static/images/ljh/jt.png" @click="returnButton()"></image>
			<view class="title">就近加油</view>
			<view class="sslan">
				<uni-search-bar bgColor="#fff" class="uni-mt-10" radius="100" placeholder="郑州市高新区" clearButton="none"
					cancelButton="none">
				</uni-search-bar>
				<view class="qhan" @click="qhms()">
					列表模式
				</view>
			</view>
		</view>




		<view class="content">
			<uni-card style="border-radius: 20rpx;">
				<!-- 地图 -->
				<map style="width: 100%; height: 400px;" :latitude="latitude" :longitude="longitude" scale="16"
					:markers="markers" @markertap="onMarkerTap" @callouttap="shopDeta" :polyline="polyline"></map>
				<view class="jyzxx">
					<view class="jyzxxLeft">
						<view class="jyzName">
							{{ nowMsg.name }}
						</view>
						<view class="jyzWz">
							{{ nowMsg.address }}
						</view>
						<view class="mdxq">
							<image src="../../../static/images/ljh/i.png" v-if="infoWindowVisible"></image>

							<view class="" @click="onClick()" v-if="infoWindowVisible">
								门店详情>>
							</view>
						</view>
					</view>
					<view class="jyzxxRight" style="margin-left: 70rpx;">
						<view style="margin-left: 70rpx;margin-bottom: 10rpx;">
							{{nowMsg.distance}}<text v-if="infoWindowVisible">m</text>
						</view>
						<!-- <image src="../../../static/images/ljh/qx.png"></image> -->
						<image :src="nowMsg.img"></image>
					</view>
				</view>
			</uni-card>
			<u-button type="primary" text="立即导航" class="tcdl" @click="getRoute"></u-button>
			<!-- <view v-if="infoWindowVisible" class="info-window">
				<text>商家名称: {{ selectedMarker.callout.content }}</text>
				<view class="link-container">
					<navigator url="/pages/index/index" open-type="switchTab">
						<text class="link">访问商家</text>
					</navigator>
				</view>
			</view> -->
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				//	经纬度，初始
				latitude: 34.826128,
				longitude: 113.558902,
				selectedMarker: '', // 存储被点击标记的信
				infoWindowVisible: false, // 控制信息窗口的显示与隐藏
				nowMsg: {
					id: '',
					name: '',
					address: '',
					img: '',
					distance: '',
					latitude:'',
					longitude:''
				},
				//	地图标注
				markers: [{
					id: 999,
					latitude: 34.826128,
					longitude: 113.558902,
					width: 25,
					height: 25,
					iconPath: '../../../static/images/ljh/dw1.png',
					callout: { // 自定义一直显示的数据，自己的定位信息
						content: "我",
						color: "#fff",
						bgColor: '#000',
						borderRadius: 10,
						padding: 10,
						display: "ALWAYS",
					}
				}],
				//   地图标注结尾
				
				polyline:[]
			}
		},
		onLoad() {
			// this.getMyPosition()	//当前位置
			this.getList()
			// this.getRoute()
		},
		methods: {
			
			
			
			//	导航去某个地点
			getRoute() {
				let that = this;
				this.$http({
					url: `/tx/ws/direction/v1/driving/?from=${that.latitude},${that.longitude}&to=${that.nowMsg.latitude},${that.nowMsg.longitude}&
					output=json&callback=cb&key=UNGBZ-RWT3T-SHHXZ-VAME3-XUHPH-EBBSP`,
					method: 'GET',
					success(res) {
						// console.log(res)
						const routeData = res.data.result.routes[0].polyline;
						that.polyline = [{
							points: that.decodePolyline(routeData),
							color: "#87cefa", // 线条颜色
							width: 2, // 线条宽度
							dottedLine: false, // 是否虚线
							arrowLine: true,
							borderWidth: 2
						}];
						console.log(that.polyline)
						// console.log(that.mapContext);

					}
				})


			},

			decodePolyline(pointsArray) {
				let decodedPoints = [];
				// 起始点的纬度和经度
				let lat = pointsArray[0];
				let lng = pointsArray[1];
				// 将起始点加入到解码后的点列表中
				decodedPoints.push({
					latitude: lat,
					longitude: lng
				});
				// 遍历数组，从第2个元素开始，每次增加2个元素（即一对增量）
				for (let i = 2; i < pointsArray.length; i += 2) {
					// 每两个值为一组，表示纬度和经度的变化量（以百万分之一为单位）
					let latDelta = pointsArray[i] / 1e6;
					let lngDelta = pointsArray[i + 1] / 1e6;
					// 更新当前点的经纬度
					lat += latDelta;
					lng += lngDelta;
					// 将新的坐标点加入到解码后的点列表中
					decodedPoints.push({
						latitude: lat,
						longitude: lng
					});
				}
				return decodedPoints;
			},

			getList() {
				let that = this;
				let userId = uni.getStorageSync('user_id');
				this.$http({
					//	传入当前用户的id用于区别不同用户之间的  附近加油站
					url: '/api/petrol/petrol/listGeo/' + userId+'/加油站',
					method: 'GET',
					success(res) {
						console.log(res);
						res.data.rows.forEach(item => {
							// 为每个返回的数据项创建一个新的标注对象
							const newMarker = {
								id: item.id, // 确保每个标注都有一个唯一的ID
								name: item.name,
								address: item.address,
								// latitude: 34.826128,
								// longitude: 113.558902,
								latitude: item.latitude,
								longitude: item.longitude,
								width: 50, // 可以根据需要调整
								height: 50, // 可以根据需要调整
								iconPath: item.iconPath ||
									'../../../static/images/ljh/poi.png', // 使用默认图标如果未提供
								callout: {
									content: item.name, // 标注的显示内容
									color: '#000000',
									fontSize: 16,
									display: 'ALWAYS',
									borderRadius: 5,
									bgColor: '#ffffff',
									padding: 10
								}
							};
							// 将新标注添加到markers数组中
							that.markers.push(newMarker);
						});
						console.log(that.markers);
					}

				})
			},

			shopDeta() {
				console.log('进行跳转页面操作');
			},


			calculateDistanceInMeters(lat1, lon1, lat2, lon2) {
				const R = 6371000; // 地球半径，单位：米 结果为：米
				//const R = 6371; // 地球半径，单位：公里 结果为：公里
				const dLat = this.degToRad(lat2 - lat1);
				const dLon = this.degToRad(lon2 - lon1);
				const a =
					Math.sin(dLat / 2) * Math.sin(dLat / 2) +
					Math.cos(this.degToRad(lat1)) * Math.cos(this.degToRad(lat2)) *
					Math.sin(dLon / 2) * Math.sin(dLon / 2);
				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
				return parseFloat((R * c).toFixed(2)); // 保留两位小数; // 距离，单位：米
			},
			// 辅助函数：将角度转换为弧度
			degToRad(deg) {
				return deg * (Math.PI / 180);
			},


			// 地图标注点击事件
			onMarkerTap(e) {
				// 点击标注点时显示商家数据
				let that = this;
				this.selectedMarker = this.markers.find(obj => obj.id ===
					e.detail.markerId);
				if (this.selectedMarker) {
					this.nowMsg.id = this.selectedMarker.id;
					this.nowMsg.name = this.selectedMarker.name;
					this.nowMsg.address = this.selectedMarker.address;
					this.nowMsg.latitude = this.selectedMarker.latitude;
					this.nowMsg.longitude = this.selectedMarker.longitude;
					//	获取图片
					that.$http({
						url: '/api/petrol/petrolImage/' + this.selectedMarker.id,
						method: 'GET',
						success(res) {
							console.log(res);
							that.nowMsg.img = res.data.msg;
							console.log(that.nowMsg.img);
						}
					});

					//	计算距离
					this.nowMsg.distance = this.calculateDistanceInMeters(this.markers[0].latitude, this.markers[0]
						.longitude, this.selectedMarker.latitude, this.selectedMarker.longitude)

					console.log(this.selectedMarker);
					this.infoWindowVisible = true;
					// 这里可以添加逻辑来定位信息窗口的位置
				}
			},

			// 获取经纬度
			getMyPosition() {
				let that = this;
				uni.getLocation({
					success(resp) {
						//console.log(resp);
						that.longitude = resp.longitude;
						that.latitude = resp.latitude;
					},
					fail() {
						console.log('定位失败')
					}
				})
			},

			qhms() {
				uni.$u.route('/pages/ljh/refuelNearby/refuelNearby')
			},
			returnButton() {
				// uni.$u.route('/pages/index/index')
				uni.$u.route({
					url: '/pages/index/index',
					type: 'tab'
				})
			},
			onClick() {
				uni.$u.route('/pages/ljh/GasStationDetails/GasStationDetails?id=' + this.nowMsg.id)
			}
		}
	}
</script>

<style>
	.tiaozhuan {
		position: absolute;
		color: white;
		font-size: 50rpx;
		top: 50rpx;
		left: 20rpx;
		width: 50rpx;
		height: 50rpx;
	}

	.tcdl {
		width: 80%;
		border-radius: 40rpx;
		margin-bottom: 40rpx;
	}

	.content {
		width: 100%;
		height: 600px;
		position: absolute;
		top: 280rpx;
	}

	map {
		height: 600rpx;
	}

	.jyzxxRight {
		margin-top: 55rpx;
		margin-left: 40rpx;
	}

	.jyzxx {
		display: flex;
	}

	.jyzxxRight image {
		width: 220rpx;
		height: 140rpx;
	}

	.mdxq {
		font-size: 26rpx;
		margin-top: 20rpx;
		height: 40rpx;
		line-height: 40rpx;
		color: blue;
		display: flex;
	}

	.jyzWz {
		font-size: 26rpx;
		margin-top: 20rpx;
	}

	.jyzName {
		font-size: 36rpx;
		font-weight: bolder;
		margin-top: 40rpx;
	}

	.mdxq image {
		width: 40rpx;
		height: 40rpx;
		margin-right: 10rpx;
	}

	.uni-mt-10 {
		margin-top: 0rpx;
		margin-left: 10rpx;
		width: 75%;
	}

	.sslan {
		display: flex;
	}

	.qhan {
		text-align: center;
		line-height: 100rpx;
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		font-size: 12rpx;
		color: white;
		background-color: blueviolet;
		box-shadow: rgba(0, 0, 0, 0.25) 0px 54px 55px, rgba(0, 0, 0, 0.12) 0px -12px 30px, rgba(0, 0, 0, 0.12) 0px 4px 6px, rgba(0, 0, 0, 0.17) 0px 12px 13px, rgba(0, 0, 0, 0.09) 0px -3px 5px;
	}

	.top {
		width: 100%;
		height: 450rpx;

	}

	.title {
		width: 100%;
		color: white;
		text-align: center;
		padding: 50rpx 0rpx;
		font-size: 35rpx;
	}
</style>